import {useSyncExternalStore} from "react";

export const useStorage = (key:string,value:any) => {
    // 订阅者
const subscribe = (callback:()=>void)=>{
    window.addEventListener('storage',callback)
    //返回取消订阅
    return ()=>{
        window.removeEventListener('storage',callback)
    }
}
const getSnapshot = () => {
    console.log(' JSON.parse( localStorage.getItem(key)!) || value', JSON.parse( localStorage.getItem(key)!) || value)
    return JSON.parse( localStorage.getItem(key)!) ?? value
}
    const res = useSyncExternalStore(subscribe,getSnapshot)
    const updateStorage = (value:any):void => {
        localStorage.setItem(key,JSON.stringify(value))
        window.dispatchEvent(new StorageEvent("storage"))
    }
    return [res,updateStorage,getSnapshot]
}
